﻿using System;
using System.Collections.Generic;
using System.IO;

namespace dk.Helper.Base.Core
{
    public class PlayerDataReader : IPlayerDataReader
    {
        private readonly IVillages villages;

        /// <summary>
        /// Initializes a new instance of the <see cref="T:System.Object"/> class.
        /// </summary>
        public PlayerDataReader(IVillages villages)
        {
            this.villages = villages;
        }

        #region IPlayerDataReader Members

        /// <summary>
        /// Creates the players.
        /// </summary>
        /// <param name="datafile">The datafile.</param>
        /// <returns></returns>
        public IPlayers CreatePlayers(string datafile)
        {
            if (!File.Exists(datafile))
                return null;

            IPlayerParser playerParser = new PlayerParser();
            IPlayers players = new Players();
            using (TextReader textReader = new StreamReader(datafile))
            {
                string data;
                while ((data = textReader.ReadLine()) != null)
                {
                    IPlayer player = playerParser.CreatePlayer(data, villages);
                    if (player == null)
                    {
                        throw new InvalidOperationException("Failed to parse player: " + data);
                    }
                    players.PlayersByID.Add(player.ID, player);
                    players.PlayersByName.Add(player.Name, player);
                    if (!players.PlayersByAllyID.ContainsKey(player.AllyID))
                        players.PlayersByAllyID.Add(player.AllyID, new List<IPlayer>());
                    if (!players.PlayersByAllyID[player.AllyID].Contains(player))
                        players.PlayersByAllyID[player.AllyID].Add(player);
                }
            }
            return players;
        }

        #endregion
    }
}